/**
 * 这里存放canvas组建的旧代码，已禁用，仅用于备份
 */
import { useEffect, useRef } from 'react'
import { drawShape } from '@/utils/shapeUtils'

function Canvas({ activePenId, onClear, penColor, selectedShape, selectedLine, selectedText, drawMode }) {
  const canvasRef = useRef(null)
  const textAreasRef = useRef([]) // 存储所有文本框textarea引用

  // 选择模式相关状态
  const selectedItems = useRef([])     // 当前选中的项目列表（支持多选）
  const isDragging = useRef(false)     // 是否正在拖动
  const isResizing = useRef(false)     // 是否正在调整大小
  const dragStartPos = useRef(null)    // 拖动开始位置
  const originalItemPos = useRef(null) // 原始项目位置
  const resizeHandle = useRef(null)    // 当前调整大小的控制点

  // 形状绘制相关状态
  const shapeStartPos = useRef(null)   // 存储形状开始位置
  const shapeEndPos = useRef(null)     // 存储形状结束位置

  // 连接线绘制相关状态
  const lineStartPos = useRef(null)    // 存储连接线开始位置
  const lineEndPos = useRef(null)      // 存储连接线结束位置
  const linePoints = useRef([])        // 存储折线的所有点

  // 文本框相关状态
  const textStartPos = useRef(null)    // 存储文本框开始位置
  const textEndPos = useRef(null)      // 存储文本框结束位置
  const editingText = useRef(null)     // 当前正在编辑的文本框

  // 画笔绘制相关状态
  const currentPath = useRef([])       // 用于存储当前笔画的所有线段
  const getPenStyle = (activePenId) => {
    switch (activePenId) {
      case 1:
        return {
          strokeStyle: '#000',  // 线颜色,默认黑色
          lineWidth: 2,         // 线宽
          lineCap: 'round',     // 线帽
          setLineDash: [],      // 虚线模式
          globalAlpha: 1        // 透明度
        }
      case 2:
        return {
          strokeStyle: '#34306c',
          lineWidth: 1.25,
          lineCap: 'butt',
          setLineDash: [],
          globalAlpha: 1
        }
      case 3:
        return {
          strokeStyle: '#808080',
          lineWidth: 1,
          lineCap: 'round',
          setLineDash: [2, 4],
          globalAlpha: 0.5
        }
      case 4:
        return {
          strokeStyle: '#000',
          lineWidth: 9,
          lineCap: 'round',
          setLineDash: [5, 10],
          globalAlpha: 0.7
        }
      case 5:
        return {
          strokeStyle: '#FFFF00',
          lineWidth: 15,
          lineCap: 'square',
          setLineDash: [],
          globalAlpha: 0.5
        }
      case 6:
        return {
          strokeStyle: '#f0f0f0',
          lineWidth: 15,
          lineCap: 'round',
          setLineDash: [],
          globalAlpha: 1
        }
      default:
        return {}
    }
  }

  // 撤销/重做栈
  const undoStack = useRef([])         // 撤销栈
  const redoStack = useRef([])         // 重做栈

  // 绘制箭头的辅助函数
  const drawArrow = (ctx, fromX, fromY, toX, toY, arrowSize = 10) => {
    const angle = Math.atan2(toY - fromY, toX - fromX)
    const arrowAngle1 = angle - Math.PI / 6
    const arrowAngle2 = angle + Math.PI / 6
    
    ctx.beginPath()
    ctx.moveTo(toX, toY)
    ctx.lineTo(toX - arrowSize * Math.cos(arrowAngle1), toY - arrowSize * Math.sin(arrowAngle1))
    ctx.moveTo(toX, toY)
    ctx.lineTo(toX - arrowSize * Math.cos(arrowAngle2), toY - arrowSize * Math.sin(arrowAngle2))
    ctx.stroke()
  }

  // 创建或更新文本输入框（始终保留在DOM中）
  const createOrUpdateTextInput = (textData) => {
    const canvas = canvasRef.current
    const rect = canvas.getBoundingClientRect()
    
    // 查找是否已有对应的textarea
    let input = textAreasRef.current.find(ta => ta.dataset.id === textData.id)
    
    // 如果不存在则创建新的textarea
    if (!input) {
      input = document.createElement('textarea')
      input.dataset.id = textData.id  // 用唯一ID关联数据
      input.style.left = `${rect.left + textData.x}px`;
      input.style.top = `${rect.top + textData.y}px`;
      input.style.width = `${textData.width}px`;
      input.style.height = `${textData.height}px`;
      input.style.position = 'absolute'
      input.style.border = '1px solid #ccc'  // textarea边框作为文本框边框
      input.style.outline = 'none'
      input.style.background = 'transparent'  // 强制透明背景
      input.style.resize = 'none'
      input.style.overflow = 'auto'
      input.style.zIndex = '1000'
      input.style.padding = '5px'
      input.style.boxSizing = 'border-box'
      input.style.lineHeight = '1.2'
      input.placeholder = '输入文字...'
      input.wrap = 'soft'  // 确保textarea不自动添加换行符
      
      // 添加事件监听
      const handleInput = () => {
        textData.text = input.value
        redrawCanvas() // 文本变化时重绘Canvas，确保同步
      }
      
      const handleFocus = () => {
        editingText.current = textData  // 表示正在编辑状态
        input.style.borderColor = '#007bff'
      }
      
      const handleBlur = () => {
        editingText.current = null  // 表示为非编辑状态
        input.style.borderColor = '#ccc'
      }

      input.addEventListener('input', handleInput)
      input.addEventListener('focus', handleFocus)
      input.addEventListener('blur', handleBlur)

      document.body.appendChild(input)
      textAreasRef.current.push(input)
    }
    
    // 更新textarea属性
    input.style.left = `${rect.left + textData.x}px`
    input.style.top = `${rect.top + textData.y}px`
    input.style.width = `${textData.width}px`
    input.style.height = `${textData.height}px`
    input.style.fontSize = `${textData.fontSize}px`
    input.style.fontFamily = textData.fontFamily
    input.style.color = textData.textColor
    input.value = textData.text || ''
    
    return input
  }

  // 移除文本输入框
  const removeTextInput = (textId) => {
    const index = textAreasRef.current.findIndex(ta => ta.dataset.id === textId)
    if (index !== -1) {
      const input = textAreasRef.current[index]
      document.body.removeChild(input)
      textAreasRef.current.splice(index, 1)
    }
  }

  // 优化的文本换行逻辑：根据文本框宽度自动换行
  const getWrappedText = (ctx, text, maxWidth) => {
    const words = text.split(''); // 按字符分割，确保任何位置都能换行
    const lines = [];
    let currentLine = words[0] || '';

    // 如果没有文字，直接返回空数组
    if (words.length === 0) return [];

    // 逐个字符添加并检查宽度
    for (let i = 1; i < words.length; i++) {
      const word = words[i];
      const width = ctx.measureText(currentLine + word).width;
      
      // 如果加上当前字符没有超过最大宽度，则添加到当前行
      if (width < maxWidth) {
        currentLine += word;
      } else {
        // 超过最大宽度则换行
        lines.push(currentLine);
        currentLine = word;
      }
    }

    // 添加最后一行
    if (currentLine) {
      lines.push(currentLine);
    }

    return lines;
  }

  // 绘制文字到Canvas（方便导出图片）
  const drawTextToCanvas = (ctx, textData) => {
    ctx.save()
    // 仅在非编辑状态下绘制文字：防止编辑状态下显示重影
    if (editingText.current) {
      return
    }
    ctx.fillStyle = textData.textColor
    ctx.font = `${textData.fontSize}px ${textData.fontFamily}`
    ctx.textBaseline = 'top'
    
    // 计算可用宽度（减去内边距）
    const padding = 10; // 左右内边距总和
    const maxWidth = textData.width - padding;
    
    // 获取自动换行后的文本行
    const lines = getWrappedText(ctx, textData.text || '', maxWidth, textData.fontSize);
    
    // 绘制所有行
    lines.forEach((line, i) => {
      ctx.fillText(line, textData.x + 5, textData.y + 5 + i * textData.fontSize * 1.2)
    })
    ctx.restore()
  }

  // 检测点击位置是否在某个项目上
  const getItemAtPosition = (x, y) => {
    // 从后往前检查（后绘制的在上层）
    for (let i = undoStack.current.length - 1; i >= 0; i--) {
      const item = undoStack.current[i]
      
      if (item.type === 'shape') {
        if (x >= item.x && x <= item.x + item.width &&
            y >= item.y && y <= item.y + item.height) {
          return { item, index: i }
        }
      } else if (item.type === 'path') {
        for (let j = 0; j < item.points.length; j++) {
          const point = item.points[j]
          const distance = Math.sqrt((x - point.x) **2 + (y - point.y)** 2)
          if (distance <= 10) {
            return { item, index: i }
          }
        }
      } else if (item.type === 'line') {
        if (item.lineType === 'straight') {
          const A = item.endY - item.startY
          const B = item.startX - item.endX
          const C = item.endX * item.startY - item.startX * item.endY
          const distance = Math.abs(A * x + B * y + C) / Math.sqrt(A * A + B * B)
          if (distance <= 10) {
            return { item, index: i }
          }
        } else if (item.type === 'polyline') {
          const segments = [
            // { start: { x: item.startX, y: item.startY }, end: { x: item.midX, y: item.midY } },
            // { start: { x: item.midX, y: item.midY }, end: { x: item.endX, y: item.endY } }
            // 第一段：起点 → (终点X, 起点Y)（水平段）
    { start: { x: item.startX, y: item.startY }, end: { x: item.midX, y: item.midY } },
    // 第二段：(终点X, 起点Y) → 终点（垂直段）
    { start: { x: item.midX, y: item.midY }, end: { x: item.endX, y: item.endY } }
          ]
          
          for (const segment of segments) {
            const A = segment.end.y - segment.start.y
            const B = segment.start.x - segment.end.x
            const C = segment.end.x * segment.start.y - segment.start.x * segment.end.y
            const distance = Math.abs(A * x + B * y + C) / Math.sqrt(A * A + B * B)
            if (distance <= 10) {
              return { item, index: i }
            }
          }
        }
      } else if (item.type === 'text') {
        if (x >= item.x && x <= item.x + item.width &&
            y >= item.y && y <= item.y + item.height) {
          return { item, index: i }
        }
      }
    }
    return null
  }

  // 检测是否点击了控制点
  const getResizeHandleAtPosition = (x, y) => {
    if (selectedItems.current.length !== 1) return null
    
    const item = selectedItems.current[0]
    const handleSize = 8
    
    if (item.type === 'shape' || item.type === 'text') {
      const handles = [
        { x: item.x - handleSize/2, y: item.y - handleSize/2, type: 'nw' },
        { x: item.x + item.width/2 - handleSize/2, y: item.y - handleSize/2, type: 'n' },
        { x: item.x + item.width - handleSize/2, y: item.y - handleSize/2, type: 'ne' },
        { x: item.x - handleSize/2, y: item.y + item.height/2 - handleSize/2, type: 'w' },
        { x: item.x + item.width - handleSize/2, y: item.y + item.height/2 - handleSize/2, type: 'e' },
        { x: item.x - handleSize/2, y: item.y + item.height - handleSize/2, type: 'sw' },
        { x: item.x + item.width/2 - handleSize/2, y: item.y + item.height - handleSize/2, type: 's' },
        { x: item.x + item.width - handleSize/2, y: item.y + item.height - handleSize/2, type: 'se' }
      ]
      
      for (const handle of handles) {
        if (x >= handle.x && x <= handle.x + handleSize &&
            y >= handle.y && y <= handle.y + handleSize) {
          return handle.type
        }
      }
    }
    return null
  }

  // 绘制控制点
  const drawResizeHandles = (ctx, item) => {
    const handleSize = 8
    ctx.fillStyle = '#ffffff'
    ctx.strokeStyle = '#007bff'
    ctx.lineWidth = 1
    
    if (item.type === 'shape' || item.type === 'text') {
      const handles = [
        { x: item.x - handleSize/2, y: item.y - handleSize/2 },
        { x: item.x + item.width/2 - handleSize/2, y: item.y - handleSize/2 },
        { x: item.x + item.width - handleSize/2, y: item.y - handleSize/2 },
        { x: item.x - handleSize/2, y: item.y + item.height/2 - handleSize/2 },
        { x: item.x + item.width - handleSize/2, y: item.y + item.height/2 - handleSize/2 },
        { x: item.x - handleSize/2, y: item.y + item.height - handleSize/2 },
        { x: item.x + item.width/2 - handleSize/2, y: item.y + item.height - handleSize/2 },
        { x: item.x + item.width - handleSize/2, y: item.y + item.height - handleSize/2 }
      ]
      
      for (const handle of handles) {
        ctx.fillRect(handle.x, handle.y, handleSize, handleSize)
        ctx.strokeRect(handle.x, handle.y, handleSize, handleSize)
      }
    }
  }
  
  // 画布尺寸自适应
  useEffect(() => {
    const canvas = canvasRef.current
    const setCanvasSize = () => {
      canvas.width = window.innerWidth
      canvas.height = window.innerHeight
    }
    setCanvasSize()
    
    // 窗口大小变化时更新所有文本框位置
    const handleResize = () => {
      setCanvasSize()
      undoStack.current.forEach(item => {
        if (item.type === 'text') {
          createOrUpdateTextInput(item)
        }
      })
    }
    
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  // 键盘事件监听
  useEffect(() => {
    const handleKeyDown = (e) => {
      // 删除键删除选中的项目
      if (e.key === 'Delete' || e.key === 'Backspace') {
        if (selectedItems.current.length > 0) {
          for (const selectedItem of selectedItems.current) {
            const index = undoStack.current.indexOf(selectedItem)
            if (index > -1) {
              undoStack.current.splice(index, 1)
              
              // 如果是文本框，同时移除对应的textarea
              if (selectedItem.type === 'text') {
                removeTextInput(selectedItem.id)
              }
            }
          }
          selectedItems.current = []
          redrawCanvas()
        }
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [])

  // 暴露方法给父组件
  useEffect(() => {
    if (onClear) {
      onClear(
        clearCanvas,
        undo,
        redo
      )
    }
  }, [onClear])

  // 鼠标按下事件
  const startDrawing = (e) => {
    const canvas = canvasRef.current
    const rect = canvas.getBoundingClientRect()
    const pos = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    }

    switch (drawMode) {
      case 'select': {
        // 首先检查是否点击了控制点
        const resizeHandleType = getResizeHandleAtPosition(pos.x, pos.y)
        if (resizeHandleType) {
          isResizing.current = true
          resizeHandle.current = resizeHandleType
          dragStartPos.current = pos
          if (selectedItems.current[0].type === 'shape' || selectedItems.current[0].type === 'text') {
            originalItemPos.current = {
              x: selectedItems.current[0].x,
              y: selectedItems.current[0].y,
              width: selectedItems.current[0].width,
              height: selectedItems.current[0].height
            }
          }
          break
        }
        
        // 检查是否点击了已选中的项目
        const clickedItem = getItemAtPosition(pos.x, pos.y)
        if (clickedItem) {
          // 检查是否按住Ctrl键进行多选
          const isMultiSelect = e.ctrlKey || e.metaKey
          
          if (isMultiSelect) {
            // 多选模式
            const existingIndex = selectedItems.current.findIndex(item => item === clickedItem.item)
            if (existingIndex >= 0) {
              // 如果已选中，则取消选择
              selectedItems.current.splice(existingIndex, 1)
            } else {
              // 如果未选中，则添加到选择列表
              selectedItems.current.push(clickedItem.item)
            }
          } else {
            // 单选模式
            selectedItems.current = [clickedItem.item]
          }
          
          // 如果是文本框，点击时聚焦
          if (clickedItem.item.type === 'text') {
            const input = textAreasRef.current.find(ta => ta.dataset.id === clickedItem.item.id)
            if (input) input.focus()
          }
          
          isDragging.current = true
          dragStartPos.current = pos
          
          // 保存所有选中项目的原始位置
          originalItemPos.current = selectedItems.current.map(item => {
            if (item.type === 'shape') {
              return { type: 'shape', x: item.x, y: item.y }
            } else if (item.type === 'path') {
              return { type: 'path', points: [...item.points] }
            } else if (item.type === 'line') {
              const linePos = {
                type: 'line',
                startX: item.startX,
                startY: item.startY,
                endX: item.endX,
                endY: item.endY
              }
              if (item.lineType === 'polyline') {
                linePos.midX = item.midX
                linePos.midY = item.midY
              }
              return linePos
            } else if (item.type === 'text') {
              return { type: 'text', x: item.x, y: item.y }
            }
            return null
          }).filter(Boolean)
        } else {
          // 点击空白区域，清除选择
          selectedItems.current = []
          isDragging.current = false
          isResizing.current = false
          dragStartPos.current = null
          originalItemPos.current = null
          resizeHandle.current = null
          redrawCanvas()
        }
        break
      }
      case 'shape':
        shapeStartPos.current = pos
        shapeEndPos.current = null
        break
      case 'line':
        lineStartPos.current = pos
        lineEndPos.current = null
        linePoints.current = [pos]
        break
      case 'pen':
        if (activePenId >= 1 && activePenId <= 6) {
          currentPath.current = [pos]
        }
        break
      case 'text':
        textStartPos.current = pos
        textEndPos.current = null
        break
    }
  }

  // 鼠标移动事件
  const draw = (e) => {
    const canvas = canvasRef.current
    const ctx = canvas.getContext('2d')
    const rect = canvas.getBoundingClientRect()
    const pos = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    }

    if (drawMode === 'select' && isResizing.current && selectedItems.current.length === 1) {
      // 调整大小模式
      const deltaX = pos.x - dragStartPos.current.x
      const deltaY = pos.y - dragStartPos.current.y
      
      redrawCanvas()
      
      const ctx = canvas.getContext('2d')
      ctx.save()
      
      const item = selectedItems.current[0]
      const original = originalItemPos.current
      let newX = original.x, newY = original.y, newWidth = original.width, newHeight = original.height
      
      // 根据控制点类型调整大小
      switch (resizeHandle.current) {
        case 'nw':
          newX = original.x + deltaX
          newY = original.y + deltaY
          newWidth = original.width - deltaX
          newHeight = original.height - deltaY
          break
        case 'n':
          newY = original.y + deltaY
          newHeight = original.height - deltaY
          break
        case 'ne':
          newY = original.y + deltaY
          newWidth = original.width + deltaX
          newHeight = original.height - deltaY
          break
        case 'w':
          newX = original.x + deltaX
          newWidth = original.width - deltaX
          break
        case 'e':
          newWidth = original.width + deltaX
          break
        case 'sw':
          newX = original.x + deltaX
          newWidth = original.width - deltaX
          newHeight = original.height + deltaY
          break
        case 's':
          newHeight = original.height + deltaY
          break
        case 'se':
          newWidth = original.width + deltaX
          newHeight = original.height + deltaY
          break
      }
      
      // 确保最小尺寸
      if (newWidth > 10 && newHeight > 10) {
        if (item.type === 'shape') {
          drawShape(ctx, item.shapeType, newX, newY, newWidth, newHeight, item.style)
        } else if (item.type === 'text') {
          // 更新文本框数据
          item.x = newX
          item.y = newY
          item.width = newWidth
          item.height = newHeight
          // 更新textarea位置和大小
          createOrUpdateTextInput(item)
        }
      }
      
      ctx.restore()
    } else if (drawMode === 'select' && isDragging.current && selectedItems.current.length > 0) {
      // 选择模式：拖动选中的项目
      const deltaX = pos.x - dragStartPos.current.x
      const deltaY = pos.y - dragStartPos.current.y
      
      redrawCanvas()
      
      const ctx = canvas.getContext('2d')
      ctx.save()
      
      // 为每个项目计算新的位置
      for (let i = 0; i < selectedItems.current.length; i++) {
        const item = selectedItems.current[i]
        const originalPos = originalItemPos.current[i]
        
        if (item.type === 'shape' && originalPos.type === 'shape') {
          // 拖动形状（图形）
          const newX = originalPos.x + deltaX
          const newY = originalPos.y + deltaY
          drawShape(ctx, item.shapeType, newX, newY, item.width, item.height, item.style)
        } else if (item.type === 'path' && originalPos.type === 'path') {
          // 拖动路径（笔画）
          ctx.beginPath()
          for (let j = 0; j < originalPos.points.length; j++) {
            const point = originalPos.points[j]
            const newX = point.x + deltaX
            const newY = point.y + deltaY
            if (j === 0) {
              ctx.moveTo(newX, newY)
            } else {
              ctx.lineTo(newX, newY)
            }
          }
          ctx.strokeStyle = item.style.strokeStyle
          ctx.lineWidth = item.style.lineWidth
          ctx.lineCap = item.style.lineCap
          ctx.setLineDash(item.style.setLineDash)
          ctx.globalAlpha = item.style.globalAlpha
          ctx.stroke()
        } else if (item.type === 'line' && originalPos.type === 'line') {
          // 拖动连接线
          const newStartX = originalPos.startX + deltaX
          const newStartY = originalPos.startY + deltaY
          const newEndX = originalPos.endX + deltaX
          const newEndY = originalPos.endY + deltaY
          
          ctx.strokeStyle = item.style.strokeStyle
          ctx.lineWidth = item.style.lineWidth
          ctx.lineCap = item.style.lineCap
          
          if (item.lineType === 'straight') {
            // 绘制直线
            ctx.beginPath()
            ctx.moveTo(newStartX, newStartY)
            ctx.lineTo(newEndX, newEndY)
            ctx.stroke()
            
            // 如果有箭头，绘制箭头
            if (item.hasArrow) {
              drawArrow(ctx, newStartX, newStartY, newEndX, newEndY)
            }
          } else if (item.lineType === 'polyline') {
            // 绘制折线
            // const newMidX = originalPos.midX + deltaX
            // const newMidY = originalPos.midY + deltaY
            // 固定方向转折：水平→垂直（转折点为 (终点X, 起点Y)）
            const newMidX = pos.x; // 转折点X坐标 = 终点X（水平对齐终点）
            const newMidY = lineStartPos.current.y; // 转折点Y坐标 = 起点Y（垂直对齐起点）
            
            ctx.beginPath()
            ctx.moveTo(newStartX, newStartY)
            ctx.lineTo(newMidX, newMidY)
            ctx.lineTo(newEndX, newEndY)
            ctx.stroke()
            
            // 如果有箭头，绘制箭头
            if (item.hasArrow) {
              drawArrow(ctx, newMidX, newMidY, newEndX, newEndY)
            }
          }
        } else if (item.type === 'text' && originalPos.type === 'text') {
          // 拖动文本框
          const newX = originalPos.x + deltaX
          const newY = originalPos.y + deltaY
          // 更新文本框数据
          item.x = newX
          item.y = newY
          // 更新textarea位置
          createOrUpdateTextInput(item)
        }
      }
      
      ctx.restore()
    } else if (drawMode === 'shape' && selectedShape && shapeStartPos.current) {
      // 形状绘制模式：实时更新结束位置
      shapeEndPos.current = pos
      redrawCanvas()

      ctx.save()
      const startX = shapeStartPos.current.x
      const startY = shapeStartPos.current.y
      const width = Math.abs(pos.x - startX)
      const height = Math.abs(pos.y - startY)
      const x = Math.min(startX, pos.x)
      const y = Math.min(startY, pos.y)
      
      drawShape(ctx, selectedShape.type, x, y, width, height, {
        strokeStyle: '#000',
        lineWidth: 2,
        fillStyle: 'rgba(255, 255, 255, 0.1)'
      })
      ctx.restore()
    } else if (drawMode === 'line' && selectedLine && lineStartPos.current) {
      // 连接线绘制模式：实时更新结束位置
      lineEndPos.current = pos
      
      redrawCanvas()

      ctx.save()
      ctx.strokeStyle = '#000'
      ctx.lineWidth = 2
      ctx.lineCap = 'round'
      
      if (selectedLine.type === 'straight') {
        ctx.beginPath()
        ctx.moveTo(lineStartPos.current.x, lineStartPos.current.y)
        ctx.lineTo(pos.x, pos.y)
        ctx.stroke()
        
        if (selectedLine.hasArrow) {
          drawArrow(ctx, lineStartPos.current.x, lineStartPos.current.y, pos.x, pos.y)
        }
      } else if (selectedLine.type === 'polyline') {
        // const midX = (lineStartPos.current.x + pos.x) / 2
        // const midY = (lineStartPos.current.y + pos.y) / 2
        // 固定方向转折：水平→垂直（转折点为 (终点X, 起点Y)）
        const midX = pos.x; // 转折点X = 终点X
        const midY = lineStartPos.current.y; // 转折点Y = 起点Y
        
        ctx.beginPath()
        ctx.moveTo(lineStartPos.current.x, lineStartPos.current.y)
        ctx.lineTo(midX, midY)
        ctx.lineTo(pos.x, pos.y)
        ctx.stroke()
        
        if (selectedLine.hasArrow) {
          drawArrow(ctx, midX, midY, pos.x, pos.y)
        }
      }
      
      ctx.restore()
    } else if (drawMode === 'text' && selectedText && textStartPos.current) {
      // 文本框绘制模式：实时更新结束位置
      textEndPos.current = pos
      redrawCanvas()

      ctx.save()
      const startX = textStartPos.current.x
      const startY = textStartPos.current.y
      const width = Math.abs(pos.x - startX)
      const height = Math.abs(pos.y - startY)
      const x = Math.min(startX, pos.x)
      const y = Math.min(startY, pos.y)
      
      // 绘制文本框预览虚线框
      ctx.strokeStyle = '#000'
      ctx.lineWidth = 1
      ctx.setLineDash([5, 5])
      ctx.strokeRect(x, y, width, height)
      
      // 绘制提示文字
      ctx.fillStyle = '#999'
      ctx.font = `${selectedText.fontSize || 16}px Arial`
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText('释放鼠标创建文本框', x + width/2, y + height/2)
      
      ctx.restore()
    } else if (drawMode === 'pen' && currentPath.current.length > 0) {
      // 画笔绘制逻辑
      const lastPos = currentPath.current[currentPath.current.length - 1]
      currentPath.current.push(pos)

      const penStyle = getPenStyle(activePenId)
      const strokeStyle = activePenId === 6 ? '#f0f0f0' : penColor || penStyle.strokeStyle

      ctx.save()
      ctx.beginPath()
      ctx.moveTo(lastPos.x, lastPos.y)
      ctx.lineTo(pos.x, pos.y)
      ctx.strokeStyle = strokeStyle
      ctx.lineWidth = penStyle.lineWidth
      ctx.lineCap = penStyle.lineCap
      ctx.setLineDash(penStyle.setLineDash)
      ctx.globalAlpha = penStyle.globalAlpha
      ctx.stroke()
      ctx.restore()
    }
  }

  // 鼠标抬起事件
  const stopDrawing = (e) => {
    if (drawMode === 'select' && isResizing.current && selectedItems.current.length === 1) {
      // 完成调整大小
      const canvas = canvasRef.current
      const rect = canvas.getBoundingClientRect()
      const endPos = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      }
      const deltaX = endPos.x - dragStartPos.current.x
      const deltaY = endPos.y - dragStartPos.current.y
      
      const item = selectedItems.current[0]
      const original = originalItemPos.current
      
      // 根据控制点类型更新尺寸
      switch (resizeHandle.current) {
        case 'nw':
          item.x = original.x + deltaX
          item.y = original.y + deltaY
          item.width = Math.max(10, original.width - deltaX)
          item.height = Math.max(10, original.height - deltaY)
          break
        case 'n':
          item.y = original.y + deltaY
          item.height = Math.max(10, original.height - deltaY)
          break
        case 'ne':
          item.y = original.y + deltaY
          item.width = Math.max(10, original.width + deltaX)
          item.height = Math.max(10, original.height - deltaY)
          break
        case 'w':
          item.x = original.x + deltaX
          item.width = Math.max(10, original.width - deltaX)
          break
        case 'e':
          item.width = Math.max(10, original.width + deltaX)
          break
        case 'sw':
          item.x = original.x + deltaX
          item.width = Math.max(10, original.width - deltaX)
          item.height = Math.max(10, original.height + deltaY)
          break
        case 's':
          item.height = Math.max(10, original.height + deltaY)
          break
        case 'se':
          item.width = Math.max(10, original.width + deltaX)
          item.height = Math.max(10, original.height + deltaY)
          break
      }
      
      // 如果是文本框，更新textarea
      if (item.type === 'text') {
        createOrUpdateTextInput(item)
      }
      
      redrawCanvas()
      
      // 重置调整大小状态
      isResizing.current = false
      resizeHandle.current = null
      dragStartPos.current = null
      originalItemPos.current = null
    } else if (drawMode === 'select' && isDragging.current && selectedItems.current.length > 0) {
      // 选择模式：完成拖动
      const canvas = canvasRef.current
      const rect = canvas.getBoundingClientRect()
      const endPos = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      }
      const deltaX = endPos.x - dragStartPos.current.x
      const deltaY = endPos.y - dragStartPos.current.y
      
      // 更新所有选中项目的位置
      for (let i = 0; i < selectedItems.current.length; i++) {
        const item = selectedItems.current[i]
        const originalPos = originalItemPos.current[i]
        
        if (item.type === 'shape' && originalPos.type === 'shape') {
          item.x = originalPos.x + deltaX
          item.y = originalPos.y + deltaY
        } else if (item.type === 'path' && originalPos.type === 'path') {
          for (let j = 0; j < item.points.length; j++) {
            const point = originalPos.points[j]
            item.points[j] = {
              x: point.x + deltaX,
              y: point.y + deltaY
            }
          }
        } else if (item.type === 'line' && originalPos.type === 'line') {
          item.startX = originalPos.startX + deltaX
          item.startY = originalPos.startY + deltaY
          item.endX = originalPos.endX + deltaX
          item.endY = originalPos.endY + deltaY
          
          if (item.lineType === 'polyline') {
            item.midX = originalPos.midX + deltaX
            item.midY = originalPos.midY + deltaY
          }
        } else if (item.type === 'text' && originalPos.type === 'text') {
          item.x = originalPos.x + deltaX
          item.y = originalPos.y + deltaY
          // 更新textarea位置
          createOrUpdateTextInput(item)
        }
      }
      
      redrawCanvas()
      
      // 重置拖动状态
      isDragging.current = false
      dragStartPos.current = null
      originalItemPos.current = null
    } else if (drawMode === 'shape' && selectedShape && shapeStartPos.current && shapeEndPos.current) {
      // 形状绘制完成
      const canvas = canvasRef.current
      const rect = canvas.getBoundingClientRect()
      const endPos = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      }

      const startX = shapeStartPos.current.x
      const startY = shapeStartPos.current.y
      const width = Math.abs(endPos.x - startX)
      const height = Math.abs(endPos.y - startY)
      const x = Math.min(startX, endPos.x)
      const y = Math.min(startY, endPos.y)

      if (width > 5 && height > 5) {
        const shapeData = {
          type: 'shape',
          shapeType: selectedShape.type,
          x,
          y,
          width,
          height,
          style: {
            strokeStyle: '#000',
            lineWidth: 2,
            fillStyle: 'rgba(255, 255, 255, 0.1)'
          }
        }
        undoStack.current.push(shapeData)
        redoStack.current = []
        redrawCanvas()
      }

      shapeStartPos.current = null
      shapeEndPos.current = null
    } else if (drawMode === 'line' && selectedLine && lineStartPos.current && lineEndPos.current) {
      // 连接线绘制完成
      const canvas = canvasRef.current
      const rect = canvas.getBoundingClientRect()
      const endPos = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      }

      const startX = lineStartPos.current.x
      const startY = lineStartPos.current.y
      const endX = endPos.x
      const endY = endPos.y

      const distance = Math.sqrt((endX - startX) **2 + (endY - startY)** 2)
      if (distance > 10) {
        const lineData = {
          type: 'line',
          lineType: selectedLine.type,
          hasArrow: selectedLine.hasArrow,
          startX,
          startY,
          endX,
          endY,
          style: {
            strokeStyle: '#000',
            lineWidth: 2,
            lineCap: 'round'
          }
        }
        
        if (selectedLine.type === 'polyline') {
            // lineData.midX = (startX + endX) / 2
          // lineData.midY = (startY + endY) / 2
          // 拖动时保持转折点逻辑：midX=终点X，midY=起点Y
          lineData.midX = lineData.endX;  // 始终等于终点X（水平段终点）
          lineData.midY = lineData.startY; // 始终等于起点Y（垂直段起点）
        }
        
        undoStack.current.push(lineData)
        redoStack.current = []
        redrawCanvas()
      }

      lineStartPos.current = null
      lineEndPos.current = null
      linePoints.current = []
    } else if (drawMode === 'text' && selectedText && textStartPos.current && textEndPos.current) {
      // 文本框绘制完成
      const canvas = canvasRef.current
      const rect = canvas.getBoundingClientRect()
      const endPos = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      }

      const startX = textStartPos.current.x
      const startY = textStartPos.current.y
      const width = Math.abs(endPos.x - startX)
      const height = Math.abs(endPos.y - startY)
      const x = Math.min(startX, endPos.x)
      const y = Math.min(startY, endPos.y)

      if (width > 20 && height > 20) {
        // 创建唯一ID用于关联textarea
        const textId = `text-${Date.now()}-${Math.floor(Math.random() * 1000)}`
        
        const textData = {
          id: textId,
          type: 'text',
          x,
          y,
          width,
          height,
          text: '',
          fontSize: selectedText.fontSize || 16,
          textColor: selectedText.textColor || '#000000',
          backgroundColor: 'transparent',  // 强制透明背景
          fontFamily: 'Arial'
        }
        
        undoStack.current.push(textData)
        redoStack.current = []
        
        // 创建textarea并添加到DOM
        const input = createOrUpdateTextInput(textData)
        input.focus()  // 自动聚焦
        
        redrawCanvas()
      }

      textStartPos.current = null
      textEndPos.current = null
    } else if (drawMode === 'pen' && currentPath.current.length > 1) {
      // 画笔绘制结束
      const penStyle = getPenStyle(activePenId)
      const strokeStyle = activePenId === 6 ? '#f0f0f0' : penColor || penStyle.strokeStyle
      const pathData = {
        type: 'path',
        points: [...currentPath.current],
        style: {
          strokeStyle,
          lineWidth: penStyle.lineWidth,
          lineCap: penStyle.lineCap,
          setLineDash: [...penStyle.setLineDash],
          globalAlpha: penStyle.globalAlpha
        }
      }
      undoStack.current.push(pathData)
      redoStack.current = []
      currentPath.current = []
    }
  }

  // 清空画布
  const clearCanvas = () => {
    const canvas = canvasRef.current
    const ctx = canvas.getContext('2d')
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    
    // 移除所有textarea
    textAreasRef.current.forEach(input => {
      document.body.removeChild(input)
    })
    textAreasRef.current = []
    
    undoStack.current = []
    redoStack.current = []
  }

  // 重绘画布
  const redrawCanvas = () => {
    const canvas = canvasRef.current
    const ctx = canvas.getContext('2d')
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // 重绘所有已保存的内容
    for (const item of undoStack.current) {
      if (item.type === 'shape') {
        ctx.save()
        drawShape(ctx, item.shapeType, item.x, item.y, item.width, item.height, item.style)
        ctx.restore()
      } else if (item.type === 'path') {
        ctx.save()
        ctx.beginPath()
        ctx.moveTo(item.points[0].x, item.points[0].y)
        for (let i = 1; i < item.points.length; i++) {
          ctx.lineTo(item.points[i].x, item.points[i].y)
        }
        ctx.strokeStyle = item.style.strokeStyle
        ctx.lineWidth = item.style.lineWidth
        ctx.lineCap = item.style.lineCap
        ctx.setLineDash(item.style.setLineDash)
        ctx.globalAlpha = item.style.globalAlpha
        ctx.stroke()
        ctx.restore()
      } else if (item.type === 'line') {
        ctx.save()
        ctx.strokeStyle = item.style.strokeStyle
        ctx.lineWidth = item.style.lineWidth
        ctx.lineCap = item.style.lineCap
        
        if (item.lineType === 'straight') {
          ctx.beginPath()
          ctx.moveTo(item.startX, item.startY)
          ctx.lineTo(item.endX, item.endY)
          ctx.stroke()
          
          if (item.hasArrow) {
            drawArrow(ctx, item.startX, item.startY, item.endX, item.endY)
          }
        } else if (item.lineType === 'polyline') {
          ctx.beginPath()
          ctx.moveTo(item.startX, item.startY)
          ctx.lineTo(item.midX, item.midY)
          ctx.lineTo(item.endX, item.endY)
          ctx.stroke()
          
          if (item.hasArrow) {
            drawArrow(ctx, item.midX, item.midY, item.endX, item.endY)
          }
        }
        
        ctx.restore()
      } else if (item.type === 'text') {
        // 绘制文字到Canvas（用于导出）
        drawTextToCanvas(ctx, item)
      }
    }
    
    // 绘制选择框和控制点
    if (drawMode === 'select' && selectedItems.current.length > 0) {
      ctx.save()
      
      for (const item of selectedItems.current) {
        if (item.type === 'shape') {
          ctx.strokeStyle = '#007bff'
          ctx.lineWidth = 2
          ctx.setLineDash([5, 5])
          ctx.strokeRect(item.x - 2, item.y - 2, item.width + 4, item.height + 4)
          
          if (selectedItems.current.length === 1) {
            drawResizeHandles(ctx, item)
          }
        } else if (item.type === 'path') {
          ctx.strokeStyle = '#007bff'
          ctx.lineWidth = 2
          ctx.setLineDash([5, 5])
          let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
          for (const point of item.points) {
            minX = Math.min(minX, point.x)
            minY = Math.min(minY, point.y)
            maxX = Math.max(maxX, point.x)
            maxY = Math.max(maxY, point.y)
          }
          ctx.strokeRect(minX - 2, minY - 2, maxX - minX + 4, maxY - minY + 4)
        } else if (item.type === 'line') {
          ctx.strokeStyle = '#007bff'
          ctx.lineWidth = 2
          ctx.setLineDash([5, 5])
          
          if (item.lineType === 'straight') {
            const minX = Math.min(item.startX, item.endX)
            const minY = Math.min(item.startY, item.endY)
            const maxX = Math.max(item.startX, item.endX)
            const maxY = Math.max(item.startY, item.endY)
            ctx.strokeRect(minX - 2, minY - 2, maxX - minX + 4, maxY - minY + 4)
          } else if (item.lineType === 'polyline') {
            const minX = Math.min(item.startX, item.midX, item.endX)
            const minY = Math.min(item.startY, item.midY, item.endY)
            const maxX = Math.max(item.startX, item.midX, item.endX)
            const maxY = Math.max(item.startY, item.midY, item.endY)
            ctx.strokeRect(minX - 2, minY - 2, maxX - minX + 4, maxY - minY + 4)
          }
        } else if (item.type === 'text') {
          ctx.strokeStyle = '#007bff'
          ctx.lineWidth = 2
          ctx.setLineDash([5, 5])
          ctx.strokeRect(item.x - 2, item.y - 2, item.width + 4, item.height + 4)
          
          if (selectedItems.current.length === 1) {
            drawResizeHandles(ctx, item)
          }
        }
      }
      
      ctx.restore()
    }
  }

  // 撤销操作
  const undo = () => {
    if (undoStack.current.length === 0) return
    const lastAction = undoStack.current.pop()
    redoStack.current.push(lastAction)
    
    // 如果撤销的是文本框，移除对应的textarea
    if (lastAction.type === 'text') {
      removeTextInput(lastAction.id)
    }
    
    redrawCanvas()
  }

  // 重做操作
  const redo = () => {
    if (redoStack.current.length === 0) return
    const lastAction = redoStack.current.pop()
    undoStack.current.push(lastAction)
    
    // 如果重做的是文本框，重新创建textarea
    if (lastAction.type === 'text') {
      createOrUpdateTextInput(lastAction)
    }
    
    redrawCanvas()
  }

  return (
    <canvas
      ref={canvasRef}
      onMouseDown={startDrawing}
      onMouseMove={draw}
      onMouseUp={stopDrawing}
      onMouseOut={stopDrawing}
      style={{ border: '1px solid #ccc', display: 'block' }}
    />
  )
}

export default Canvas
    